package com.jiao.datasource.track;

import cn.hutool.core.collection.CollectionUtil;
import com.jiao.comm.utils.CollectionNullUtils;
import com.jiao.datasource.parse.SQLCommand;

import java.sql.Connection;
import java.util.LinkedList;
import java.util.List;

/**
 * sql 执行监听.
 * @Author Vincent.jiao
 * @Date 2022/5/13 11:00
 */
public class SQLExecTrack {
    //一个请求会开启多个 conn, 一个 conn 会使用多次.
    private static ThreadLocal<List<SQLCommand>> commandStackLocal = new ThreadLocal<>();

    /**
     * 获取当前正在执行的sql.
     * 一个连接可能会执行多个sql，此方法只会返当前执行的，不会返回调用链.
     */
    public static SQLCommand getCurrExceSQL() {
        List<SQLCommand> commandStackList =  getExceStackLsit();
        return CollectionUtil.isEmpty(commandStackList) ? null :
                commandStackList.get(commandStackList.size() - 1);
    }

    public static List<SQLCommand> getExceStackLsit() {
        return CollectionNullUtils.getList(commandStackLocal.get());
    }

    public static void setSQLCommand(SQLCommand sqlCommand) {
        List<SQLCommand> commandStackList =  commandStackLocal.get();
        if(CollectionUtil.isEmpty(commandStackList)) {
            commandStackList = new LinkedList<>();
        }

        commandStackList.add(sqlCommand);
        commandStackLocal.set(commandStackList);
    }

    public static void clear(Connection conn) {
        List<SQLCommand> list = getExceStackLsit();
        if(CollectionUtil.isNotEmpty(list)) {
            //移除指定的 conn 的记录
            list.removeIf(item -> conn.equals(item.getSqlUnit().getConnection()));

            if(CollectionUtil.isEmpty(list)) {
                commandStackLocal.remove();
            }
        }
    }
}
